#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    bool Union(vector<vector<int>>& tables, int scr, int des)
    {
        queue<int> q;
        for (int i : tables[des]) q.push(i);
        while (q.size())
        {
            int a = q.front();
            q.pop();
            if (scr == a) return false;
            for (auto i : tables[a]) q.push(i);
        }
        tables[scr].push_back(des);
        return true;
    }
    void Print(vector<int>& ret, vector<vector<int>>& tables, int i)
    {
        for (int a : ret) if (a == i) return;
        for (int b : tables[i])
        {
            Print(ret, tables, b);
            bool bp = false;
            for (int a : ret) if (a == b) bp = true;
            if (bp) continue;
            ret.push_back(b);
        }
        ret.push_back(i);
    }
    vector<int> findOrder(int numProject, vector<vector<int> >& groups) {
        vector<vector<int>> tables(numProject);
        vector<int> ret;
        for (auto& group : groups)
        {
            if (!Union(tables, group[0], group[1])) return ret;
        }
        for (int i = 0; i < numProject; i++)
            Print(ret, tables, i);
        return ret;
    }
};